<template>
  <div class="tableIndexPage">
    <template v-if="!tableOption.noFilter">
      <MyFilter2
        ref="myFilter"
        :columns="sonColumns.filter((item) => item.filterIgnore !== true)"
        :tools="tools"
        :tools-search="toolsSearch"
        :table-key="tableOption.key"
        :table-columns-cache-key="tableOption.tableColumnsCacheKey"
        @handelSearch="handleSearch2"
        @handleClear="handleClear2"
        @dynamic="dynamic"
        @saveSetting="saveSetting"
        @clearCacheColumns="clearCacheColumns"
      >
        <template v-for="item in Object.keys($slots)" #[item]="scope">
          <slot :name="item" v-bind="scope" />
        </template>

        <template v-slot:dynamicColumn>
          <el-tooltip
            class="item"
            effect="dark"
            content="动态变更属性"
            style="float: right; margin-left: 10px"
            placement="top"
          >
            <el-popover
              placement="bottom"
              trigger="click"
              width="240"
              popper-class="dynamicColumnBox"
            >
              <el-row
                v-for="(item, myColumnsIndex) in myColumns"
                :key="item.field"
                type="flex"
                justify="space-between"
                class="dynamicColumnItem"
              >
                <el-col :span="2"
                  ><svg-icon
                    :icon-class="
                      item.fixed || !item.choose ? 'unFixation' : 'fixation'
                    "
                /></el-col>
                <el-col :span="1" />
                <el-col
                  :span="14"
                  :style="{ color: !item.choose ? '#dbdbdb' : null }"
                  >{{ item.label }}</el-col
                >
                <el-col :span="2" />
                <el-col
                  :span="2"
                  class="dynamicColumnIcon"
                  @click.native="handleFixed(item, myColumnsIndex)"
                  ><svg-icon
                    :icon-class="
                      item.fixed && item.choose ? 'fixed' : 'pushpin'
                    "
                /></el-col>
                <el-col :span="1" />
                <el-col
                  :span="2"
                  class="dynamicColumnIcon"
                  @click.native="handleIsHidden(item, myColumnsIndex)"
                  ><svg-icon :icon-class="item.choose ? 'eye-open' : 'eye'"
                /></el-col>
              </el-row>

              <el-button
                slot="reference"
                size="small"
                class="filter-item"
                type="default"
                icon="el-icon-s-grid"
              />
            </el-popover>
          </el-tooltip>
        </template>
      </MyFilter2>
    </template>
    <MyTable
      ref="table"
      :columns="sonColumns"
      :expand-row-keys="expandRowKeys"
      :options="tableOption"
      :list="list"
      :loading="loading"
      v-bind="$attrs"
      @handleSelectionChange="handleSelectionChange"
      @clickRow="clickRow"
      @dblclickRow="handleRowDblclick"
      @rowDrag="rowDrag"
      @select="handleSelect"
      @expandRow="expandRow"
    >
      <template slot="expandSlot" slot-scope="{ rowInfo }">
        <slot name="expandSlot" :rowInfo="rowInfo" />
      </template>
    </MyTable>
    <div v-show="tableOption.multi || pagination" class="totalCal">
      <template>
        <span type="text" class="btn">
          {{ "已选择【" + choosedRows + "】条" }}
        </span>
      </template>
      <template v-if="pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.CurrentPage"
          :limit.sync="listQuery.PageItems"
          :page-sizes="tableOption.pageSizes"
          @pagination="getList"
        >
          <!-- <span
          slot="statistic"
          style="float: right"
        >
          {{ statistic }}
        </span> -->
        </pagination>
      </template>
      <template v-else>
        <span type="text" class="btn">
          {{ "总共【" + total + "】条" }}
        </span>
      </template>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
// import downRequest from '@/utils/downloadRequest'
import Pagination from "@/components/Pagination";
import MyTable from "./table";
import MyFilter2 from "./filter2";
import deepCopy from "@/utils/deepCopy";
import { transformKeysToUpperCase } from "@/utils/index";

import moment from "moment";
// import { tableMixin } from './tableMixin'
export default {
  name: "TisTable", // 混入  相当把 混入对象的 属性 都 写在了当前 组件里。
  components: { MyTable, Pagination, MyFilter2 },
  // mixins: [tableMixin],
  props: {
    // url:请求
    url: {
      type: String,
      default: () => "",
    },
    // 表格列
    columns: {
      type: Array,
      default: () => [],
    },
    // 过滤条件
    filters: {
      type: Array,
      default: () => [],
    },
    // 操作类
    tools: {
      type: Array,
      default: () => [],
    },
    toolsSearch: {
      type: Array,
      default: () => [],
    },
    // 表格选择
    tableOption: {
      type: Object,
      default: () => {
        return {
          noFilter: false,
          key: undefined,
          // fixedPagination: true
        };
      },
    },
    // 分页数据
    pagination: {
      type: Boolean,
      default: () => true,
    },
    // 监听重复请求 如果重复调用，只返回最后一次结果
    isListenRepeatedRequest: {
      type: Boolean,
      default: () => false,
    },
    // 固定的过滤(比如通过传递Id去获取)
    fixedFilter: {
      type: Object,
      default: () => {},
    },
    extraFilter: {
      type: Object,
      default: () => null,
    }, // 单独传递的参数
    completeHook: {
      type: Function,
      default: () => {},
    },
    changeList: {
      type: Function,
      default: () => {},
    },
    sorters: {
      type: Array,
      default: () => [],
    },
    fixedFilterList: {
      type: Array,
      default: () => [],
    },
    expandRowKeys: {
      type: Array,
      default: () => [],
    },
    defaultGetData: {
      type: Boolean,
      default: () => true,
    },
    list: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      list: [{ id: 1 }], // 表格主体的数据
      listQuery: {
        // 分页查询
        CurrentPage: 1,
        PageItems: 10,
        // PageItems: 100
      },
      total: 0, // 总计条数
      loading: true, // 表格加载
      innerFilters: [], // 过滤条件
      innerFixFilters: [], // 固定过滤条件
      filterData: {}, // 内部数据
      isDynamic: false, // 展示列
      myColumns: [], // 手动修改列的显示的columns
      sonColumns: [],
      choosedRows: 0,
      statistic: "", // 统计的数量
      innerSorters: [],
      initFilters: [], // 初始化过滤条件
      initColumnOrder: [], // 初始化表顺序
      initTableSelectRows: [], // 初始化当前table选中的值
      initColumn: [], // 用于清空列缓存后使用， 原始的column
    };
  },
  // computed() {

  // },
  watch: {
    fixedFilter: {
      immediate: true,
      deep: true,
      handler(val, oldVal) {
        // 有fixedFilter 判断包含的值
        if (val) {
          const isNoGet = Object.values(val).some((v) => {
            return v === "" || v === undefined;
          });
          if (!isNoGet) {
            this.getList();
          } else {
            this.loading = false;
          }
        }
      },
    },
    columns: {
      immediate: true,
      deep: true,
      handler(val, oldVal) {
        if (val && val.length > 0) {
          this.initColumn = val;
          this.initTableColumn(val);
        }
      },
    },
    fixedFilterList(val) {
      this.getList();
    },
    url(val) {
      // console.log('🚀 ~ file: index.vue ~ line 236 ~ val', val)
      // this.list = list;
      this.getList();
    },
    list(val) {
      // this.list = list;
      if (this.tableOption.key) {
        if (val && val.length > 0 && this.initTableSelectRows.length > 0) {
          setTimeout(() => {
            this.handleToggleRowSelection(this.initTableSelectRows[0]);
          }, 100);
        }
      }
    },
    filterData: {
      immediate: true,
      deep: true,
      handler(val, oldVal) {
        if (val && val.length > 0) {
          this.returnFilterData(val);
        }
      },
    },
    extraFilter: {
      immediate: true,
      deep: true,
      handler(val, oldVal) {
        if (val) {
          this.getList();
        }
      },
    },
    pagination: {
      immediate: true,
      handler(val, oldVal) {
        if (!val) {
          this.listQuery.PageItems = 9999;
        }
      },
    },
  },
  mounted() {
    // 有key 说明有缓存
    if (this.tableOption.key) {
      // 有查询组件 调查询方法 没有直接getList
      if (this.$refs.myFilter) {
        this.handleSearch2();
      } else {
        this.getList();
      }
    } else {
      if (!this.fixedFilter) {
        this.getList();
      }
    }
  },

  created() {
    // this.sonColumns = this.columns
    // 需要对过滤条件进行 数据存储
    // this.columns.filter(item => item.field !== undefined).forEach((item, index) => {
    //   // 如果不在baseColumn choose设为false
    //   const isChoose = this.filterMyColumns(this.columns, item)
    //   this.$set(this.myColumns, index, { ...item, choose: isChoose })
    // })
    this.filters.map((item) => {
      this.filterData.item.field = item.value || "";
      // this.$set(this.filterData, item.field, item.value || '')
    });
  },
  methods: {
    /**
     * @description: 缓存当前分页和选中的行
     */
    cacheCurrentPageAndSelectData() {
      const selectData = this.getSelectRows();
      let temp = JSON.parse(localStorage.getItem(this.tableOption.key));
      const { CurrentPage, PageItems } = this.listQuery;
      const rowIds = [];
      selectData.filter((s) => rowIds.push(s.id));
      // 有根据table key缓存的值 为了兼容saveSetting发方法保存的数据
      const initTableSelectRows = {
        currentPage: CurrentPage,
        pageItems: PageItems,
        rowIds,
      };
      if (temp) {
        temp.initTableSelectRows = initTableSelectRows;
      } else {
        // 没有 直接赋值
        temp = {
          initTableSelectRows,
        };
      }
      localStorage.setItem(this.tableOption.key, JSON.stringify(temp));
    },
    /**
     * @description: 拿最终的columns和组件传入的columns做对比，拿到myColumns最终的选中与否
     * @param {*} baseColumns
     * @param {*} column
     */
    filterMyColumns(baseColumns, column) {
      const fieldList = baseColumns.map((item) => item.field);
      return fieldList.indexOf(column.field) > -1;
    },

    async getList() {
      //todo:需要修改
      this.list = [
        { id: 1, name: "1111" },
        { id: 2, name: "2222" },
      ];
      this.loading = false;
      // if (this.url.length === 0) {
      //   this.loading = false;
      //   return false;
      // }
      // if (!this.defaultGetData) {
      //   this.loading = false;
      //   this.setList([]);
      //   return false;
      // }

      // // 固定传入比如关联附表的ParentId
      // this.innerFixFilters = [];
      // // 固定传入比如插查询不等于的数据 List类型
      // if (this.fixedFilterList.length > 0) {
      //   this.innerFixFilters = this.initFilterListHandle(this.fixedFilterList);
      // }
      // if (this.fixedFilter !== undefined) {
      //   Object.keys(this.fixedFilter).forEach((key) => {
      //     if (this.fixedFilter[key] !== null && this.fixedFilter[key] !== "") {
      //       this.innerFixFilters.push({
      //         FieldName: key,
      //         Operator: "eq",
      //         CompareValue: this.fixedFilter[key],
      //       });
      //     }
      //   });
      // }
      // const resultFilter = [...this.innerFixFilters, ...this.innerFilters];
      // if (resultFilter.length > 0) {
      //   this.listQuery.Filters = resultFilter;
      // }
      // // 如果条件全部删除需要删除过滤条件
      // if (resultFilter.length === 0) {
      //   delete this.listQuery.Filters;
      // }

      // // 排序条件
      // this.innerSorters = [];
      // if (this.sorters !== undefined) {
      //   this.sorters
      //     .filter((item) => item.field !== undefined)
      //     .forEach((item) => {
      //       this.innerSorters.push({
      //         FieldName: item.field,
      //         SortIndex: item.sortIndex,
      //         IsDesc: item.desc,
      //       });
      //     });
      // }
      // if (this.innerSorters.length > 0) {
      //   this.listQuery.Sorters = this.innerSorters;
      // }

      // this.loading = true;

      // try {
      //   // todo 待修改
      //   let filterData = {};
      //   // 额外参数
      //   if (this.extraFilter) {
      //     filterData = {
      //       ...this.extraFilter,
      //       page: {
      //         ...this.listQuery,
      //       },
      //     };
      //   }
      //   const {
      //     data: { content, pageable },
      //   } = await request({
      //     url: this.url,
      //     data: this.extraFilter ? filterData : this.listQuery,
      //     method: "post",
      //     isListenRepeatedRequest: this.isListenRepeatedRequest,
      //   });
      //   this.total = 0;
      //   this.setList(content);
      //   this.completeHook(this.list.length);

      //   this.total = pageable.total;
      // } catch (error) {
      //   // this.loading = false
      //   // alert(error)
      // } finally {
      //   this.loading = false;
      // }
    },
    /**
     * @description: 查询条件处理
     */
    handleSearch2() {
      // 当前页面保存筛选条件

      const filterList = deepCopy(this.$refs.myFilter.filter);
      this.innerFilters = this.searchFilterListHandle(filterList);
      if (
        this.innerFilters.length > 0 &&
        this.initTableSelectRows.length === 0
      ) {
        this.listQuery.CurrentPage = 1;
      }
      this.getList();
    },
    /**
     * @description: 传入的默认查询条件输入处理
     * @param {*} filterList
     */
    initFilterListHandle(filterList) {
      const filterData = [];
      filterList.forEach((item, index) => {
        if (item.addType === "group") {
          const groupFilter = [];
          item.groupFilter.forEach((gItem) => {
            if (gItem.operator === "empty" || gItem.operator === "noEmpty") {
              groupFilter.push({
                ...gItem,
                compareValue: null,
                operator: gItem.operator === "empty" ? "eq" : "ne",
              });
            } else {
              if (
                gItem.compareValue !== "" &&
                gItem.compareValue !== undefined &&
                gItem.compareValue !== null
              ) {
                groupFilter.push({
                  ...gItem,
                });
              }
            }
          });
          if (groupFilter.length > 0) {
            filterData.push({
              andOr: item.andOr,
              addType: item.addType,
              groupFilter,
            });
          }
        } else {
          if (item.operator === "empty" || item.operator === "noEmpty") {
            filterData.push({
              ...item,
              CompareValue: null,
              Operator: item.operator === "empty" ? "eq" : "ne",
              AndOr: index === 0 ? 0 : filterList[index - 1].andOr,
            });
          } else {
            filterData.push({
              ...item,
              // AndOr: index === 0 ? 0 : filterList[index - 1].andOr
            });
          }
        }
      });
      // console.log('🚀 ~ filterData.map ~ filterData:****', filterData)

      const innerFilters = [];
      filterData.map((filterItem) => {
        if (filterItem.addType === "group") {
          const groupFilterInfo = {
            AndOr: filterItem.andOr,
            addType: filterItem.addType,
            groupFilterList: [],
          };
          filterItem.groupFilter.forEach((groupItem) => {
            if (groupItem.type === "date") {
              const transformedData = transformKeysToUpperCase(groupItem);
              const filterTypeDateList =
                this.filterTypeDateFormat(transformedData);
              groupFilterInfo.groupFilterList.push(filterTypeDateList[0]);
              groupFilterInfo.groupFilterList.push(filterTypeDateList[1]);
            } else {
              groupFilterInfo.groupFilterList.push({
                FieldName: groupItem.fieldName,
                Operator: groupItem.operator,
                CompareValue: groupItem.compareValue,
                AndOr: groupItem.andOr,
                IsList: groupItem.isList,
              });
            }
          });
          innerFilters.push(groupFilterInfo);
        } else {
          if (filterItem.type === "date") {
            const transformedData = transformKeysToUpperCase(filterItem);
            const filterTypeDateList =
              this.filterTypeDateFormat(transformedData);
            innerFilters.push(filterTypeDateList[0]);
            innerFilters.push(filterTypeDateList[1]);
          } else {
            // === '或者' ? 1 : 0
            innerFilters.push({
              FieldName: filterItem.fieldName,
              Operator: filterItem.operator,
              CompareValue: filterItem.compareValue,
              AndOr: filterItem.andOr,
              IsList: filterItem.isList,
            });
          }
        }
      });
      return innerFilters;
    },
    /**
     * @description: 手动添加查询的数据处理
     * @param {*} filterList
     */
    searchFilterListHandle(filterList) {
      const filterData = [];
      filterList.forEach((item, index) => {
        if (item.addType === "group") {
          const groupFilter = item.groupFilter.filter((gItem) => {
            if (gItem.Operator === "empty" || gItem.Operator === "noEmpty") {
              gItem.CompareValue = null;
              gItem.Operator = gItem.Operator === "empty" ? "eq" : "ne";
              return gItem;
            } else {
              return (
                gItem.CompareValue !== "" &&
                gItem.CompareValue !== undefined &&
                gItem.CompareValue !== null
              );
            }
          });
          if (groupFilter.length > 0) {
            filterData.push({
              AndOr: index === 0 ? 0 : filterList[index - 1].AndOr,
              addType: item.addType,
              groupFilter,
            });
          }
        } else {
          if (item.Operator === "empty" || item.Operator === "noEmpty") {
            filterData.push({
              ...item,
              CompareValue: null,
              Operator: item.Operator === "empty" ? "eq" : "ne",
              AndOr: index === 0 ? 0 : filterList[index - 1].AndOr,
            });
          } else {
            if (
              item.CompareValue !== "" &&
              item.CompareValue !== undefined &&
              item.CompareValue !== null
            ) {
              filterData.push({
                ...item,
                AndOr: index === 0 ? 0 : filterList[index - 1].AndOr,
              });
            }
          }
        }
      });
      const innerFilters = [];
      filterData.map((filterItem) => {
        if (filterItem.addType === "group") {
          const groupFilterInfo = {
            AndOr: filterItem.AndOr === "或者" ? 1 : 0,
            addType: filterItem.addType,
            groupFilterList: [],
          };
          filterItem.groupFilter.forEach((groupItem) => {
            if (groupItem.type === "date") {
              const filterTypeDateList = this.filterTypeDateFormat(groupItem);
              groupFilterInfo.groupFilterList.push(filterTypeDateList[0]);
              groupFilterInfo.groupFilterList.push(filterTypeDateList[1]);
            } else {
              groupFilterInfo.groupFilterList.push({
                FieldName: groupItem.FieldName,
                Operator: groupItem.Operator,
                CompareValue: groupItem.CompareValue,
                AndOr: groupItem.AndOr,
                IsList: groupItem.IsList,
              });
            }
          });
          innerFilters.push(groupFilterInfo);
        } else {
          if (filterItem.type === "date") {
            const filterTypeDateList = this.filterTypeDateFormat(filterItem);
            innerFilters.push(filterTypeDateList[0]);
            innerFilters.push(filterTypeDateList[1]);
          } else {
            innerFilters.push({
              FieldName: filterItem.FieldName,
              Operator: filterItem.Operator,
              CompareValue: filterItem.CompareValue,
              AndOr: filterItem.AndOr === "或者" ? 1 : 0,
              IsList: filterItem.IsList,
            });
          }
        }
      });
      return innerFilters;
    },
    /**
     * @description: 查询条件是date的处理
     * @param {*} item
     */
    filterTypeDateFormat(item) {
      if (item.Operator === "gt" || item.Operator === "lt") {
        return [
          {
            FieldName: item.FieldName,
            Operator: "gt",
            CompareValue: moment(item.CompareValue[0]).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
            AndOr: item.AndOr,
            IsList: item.IsList,
          },
          {
            FieldName: item.FieldName,
            Operator: "lt",
            CompareValue: moment(item.CompareValue[1]).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
            AndOr: 0,
            IsList: item.IsList,
          },
        ];
      } else {
        return [
          {
            FieldName: item.FieldName,
            Operator: "gte",
            CompareValue: moment(item.CompareValue[0]).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
            AndOr: item.AndOr,
            IsList: item.IsList,
          },
          {
            FieldName: item.FieldName,
            Operator: "lt",
            //  CompareValue: moment(item.CompareValue[1]).add(1, 'days').format('YYYY-MM-DD HH:mm:ss'),
            CompareValue: moment(item.CompareValue[1]).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
            AndOr: 0,
            IsList: item.IsList,
          },
        ];
      }
    },

    handleClear2() {
      delete this.listQuery.Filters;
      // 清空本地缓存的查询条件
      if (this.tableOption.key) {
        const userInfo = JSON.parse(sessionStorage.getItem("userName"));
        const saveLocalStorageKey = `${userInfo.userName}_${this.tableOption.key}`;
        this.initTableSelectRows = []; // 清除缓存的选中行
        localStorage.removeItem(saveLocalStorageKey); // 清除缓存
      }
      this.listQuery.CurrentPage = 1;
      this.innerFilters = [];
      this.initFilters = [];
      this.getList();
    },
    getSelectRows() {
      return this.$refs.table.$refs.multipleTable.selection;
    },
    getAllList() {
      return this.list;
    },
    refresh(cache = false) {
      if (cache) {
        this.getList();
      } else {
        this.$refs.table.$refs.multipleTable.clearSelection();
        this.getList();
      }

      // this.$refs.table.setRows()
    },
    handleSelectionChange(length, val) {
      this.choosedRows = length;
      this.$emit("handleSelectionChange", length, val);
    },
    handleRowDblclick(val) {
      this.$emit("handleRowDblclick", val);
    },
    expandRow(val) {
      this.$emit("expandRow", val);
    },
    handleSelect(val) {
      this.choosedRows = val;
      this.$emit("handleSelect", val);
    },
    setList(list) {
      this.list = [];
      // 为需要展开的table添加展开行字段标识
      if (this.tableOption.tableExpand) {
        list.forEach((row) => {
          row.details = [];
          row.loadDetails = false; // 加载成功之后在调用组件的页面更新标识
        });
      }

      this.list = list;
      this.changeList(list);
    },
    /**
     * 变化的时候搜索只在id
     */
    onChange() {
      this.handelSearch();
    },
    /**
     * @description: 列显示/隐藏
     * @param {*} item
     */
    handleIsHidden(item, index) {
      this.myColumns[index].choose = !item.choose;
      this.myColumns[index].fixed = false;
      // this.$set(this.myColumns[index], "choose", !item.choose);
      // this.$set(this.myColumns[index], "fixed", false);
      const choose = this.myColumns
        .filter((item) => item.choose === true)
        .map((item) => item.field);
      this.sonColumns = this.columns.filter((cItem) => {
        if (cItem.field === item.field) {
          cItem.fixed = false;
        }
        return choose.indexOf(cItem.field) >= 0 || cItem.field === undefined;
      });
    },
    /**
     * @description: 列固定/不固定
     * @param {*} item
     */
    handleFixed(item, index) {
      this.myColumns[index].choose = true;
      this.myColumns[index].fixed = !item.fixed;
      // this.$set(this.myColumns[index], "choose", true);
      // this.$set(this.myColumns[index], "fixed", !item.fixed);
      const choose = this.myColumns
        .filter((item) => item.choose === true)
        .map((item) => item.field);
      this.sonColumns = this.columns.filter((cItem) => {
        if (cItem.field === item.field) {
          cItem.fixed = item.fixed;
        }
        return choose.indexOf(cItem.field) >= 0 || cItem.field === undefined;
      });
    },
    // 单行触发
    clickRow(data) {
      // 注意需要深度拷贝
      const copy = deepCopy(data);
      this.$emit("clickRow", copy);
    },
    dynamic() {
      this.isDynamic = !this.isDynamic;
    },
    rowDrag(oldList, newList) {
      this.$emit("rowDrag", oldList, newList);
    },
    /**
     * @description: 保存查询条件
     */
    saveSetting() {
      if (this.tableOption.key !== undefined) {
        // 解决当没有筛选条件是点击保存设置按钮后缓存的筛选条件被干掉的问题
        const filterList = this.$refs.myFilter.filter;
        if (filterList.length > 0) {
          const initFilters = [];
          filterList.forEach((item, index) => {
            if (item.addType === "group") {
              const groupFilter = item.groupFilter.filter(
                (gItem) => gItem.FieldName !== ""
              );
              if (groupFilter.length > 0) {
                initFilters.push({
                  AndOr: item.AndOr,
                  addType: item.addType,
                  groupFilter,
                });
              }
            } else {
              if (item.FieldName !== "") {
                initFilters.push({
                  ...item,
                });
              }
            }
          });
          this.initFilters = initFilters;
          if (initFilters.length > 0) {
            const tempObject = JSON.stringify({
              initFilters,
            });
            // 添加查询条件保存，根据用户名_页面名缓存，页面加载根据缓存展示查询条件；
            const userInfo = JSON.parse(sessionStorage.getItem("userName"));
            const saveLocalStorageKey = `${userInfo.userName}_${this.tableOption.key}`;
            localStorage.setItem(saveLocalStorageKey, tempObject);
            this.$message.success("查询条件保存成功！");
          } else {
            this.$message.warning("请选择要保存的属性！");
          }
        }
        // this.cacheCurrentPageAndSelectData()
      }
    },
    /**
     * @description: 单选表格选中
     */
    handleSetCurrentRow(id) {
      this.list.forEach((l, i) => {
        if (l.id === id) {
          this.$refs.table.$refs.multipleTable.setCurrentRow(l, true);
        }
      });
    },
    /**
     * @description: 多选表格选中
     */
    handleToggleRowSelection(id) {
      this.list.forEach((l, i) => {
        if (l.id === id) {
          this.$refs.table.$refs.multipleTable.toggleRowSelection(l, true);
          // 滚动到选中的行
          this.tableScrollMove(this.$refs.table.$refs.multipleTable, i);
        }
      });
    },
    /**
     * @description: 通过表格索引 定位表格滚动的位置
     * @param {refName} table的ref值
     * @param {index} table的索引值
     */
    tableScrollMove(refName, index = 0) {
      if (!refName) return; // 不存在表格的ref vm 则返回
      const vmEl = refName.$el;
      if (!vmEl) return;
      // 计算滚动条的位置
      const targetTop = vmEl
        .querySelectorAll(".el-table__body tr")
        [index].getBoundingClientRect().top;
      const containerTop = vmEl
        .querySelector(".el-table__body")
        .getBoundingClientRect().top;
      const scrollParent = vmEl.querySelector(".el-table__body-wrapper");
      scrollParent.scrollTop = targetTop - containerTop;
    },
    /**
     * @description: 清空选择
     */
    handleClearSelectData() {
      this.$refs.table.$refs.multipleTable.clearSelection();
      this.initTableSelectRows = [];
      // 清空本地缓存的table选择数据
      if (this.tableOption.key) {
        localStorage.setItem(
          this.tableOption.key,
          JSON.stringify({
            initTableSelectRows: null,
          })
        );
      }
    },
    returnFilterData(val) {
      this.$emit("returnFilterData", val);
    },
    /**
     * @description: 清空缓存的column 使用初始column
     */
    clearCacheColumns() {
      localStorage.setItem(this.tableOption.tableColumnsCacheKey, null);
      this.initTableColumn(this.initColumn);
      this.$message.success("当前table列数据已还原！");
    },
    /**
     * @description: 初始化columns 有tableColumnsCacheKey 从本地拿 否则使用最新传入的columns
     */
    initTableColumn(column) {
      const cacheColumnField = JSON.parse(
        localStorage.getItem(this.tableOption.tableColumnsCacheKey)
      );
      if (cacheColumnField && cacheColumnField.initFields.length > 0) {
        const cacheColumns = [column[0]];
        cacheColumnField.initFields.forEach((item) => {
          column.forEach((r) => {
            if (item.field === r.field) {
              const columnRender = this.initColumn.find(
                (c) => c.field === item.field
              );
              if (columnRender) {
                if (
                  columnRender.filterOptions &&
                  columnRender.filterOptions.length > 0
                ) {
                  item.filterOptions = columnRender.filterOptions;
                }
                item.render = columnRender.render;
              }
              cacheColumns.push(item);
            }
          });
        });

        this.sonColumns = cacheColumns;
      } else {
        this.sonColumns = column;
      }

      this.myColumns = [];
      this.sonColumns
        .filter((item) => item.field !== undefined)
        .forEach((item, index) => {
          // 如果不在baseColumn choose设为false
          const isChoose = this.filterMyColumns(this.sonColumns, item);
          // this.$set(this.myColumns, index, { ...item, choose: isChoose });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.tableIndexPage {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  flex: 1;
}
.totalCal {
  margin-top: 10px !important;
  width: 100%;
  line-height: 26px;
  text-align: right;
}
::v-deep .pagination-container {
  margin-top: -15px !important;
  padding: 0 !important;
  display: inline-block;
  text-align: right;
}
.btn {
  margin-top: 10px;
  font-size: 13px;
}
</style>
<style lang="scss">
.el-popover.dynamicColumnBox {
  // top: 40px !important;
  overflow: auto;
  max-height: 88vh;
}
.dynamicColumnItem {
  margin-bottom: 5px;
}
.dynamicColumnIcon {
  text-align: right;
  cursor: pointer;
}
</style>
